package cn.s1995.sloth.app.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.s1995.sloth.bizs.constant.BizCst;
import cn.s1995.sloth.bizs.entity.HotSearch;
import cn.s1995.sloth.bizs.entity.UserHistorySearch;
import cn.s1995.sloth.bizs.service.HotSearchService;
import cn.s1995.sloth.bizs.service.UserHistorySearchService;
import cn.s1995.sloth.common.core.util.R;
import cn.s1995.sloth.common.security.annotation.Inner;
import cn.s1995.sloth.common.security.util.SecurityUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户历史搜索
 *
 * @author sloth
 * @date 2023-12-27 09:11:34
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/m/userHistorySearch")
@Tag(description = "UserHistorySearch", name = "APP-用户历史搜索模块")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class ApiUserHistorySearchController {

    private final UserHistorySearchService userHistorySearchService;

    private final HotSearchService hotSearchService;

	@ApiOperationSupport(order = 1)
	@Operation(summary = "最近搜索的关键字", description = "最近搜索的关键字")
	@GetMapping("/recent")
	public R<List<UserHistorySearch>> getRecentSearch() {
		Long uid = SecurityUtils.getUser().getId();
		List<UserHistorySearch> list = userHistorySearchService.list(
			Wrappers.lambdaQuery(UserHistorySearch.class)
					.eq(UserHistorySearch::getUid, uid)
					.orderByDesc(UserHistorySearch::getUpdateTime)
					.last(" LIMIT 10")
		);
		return R.ok(list);
	}

	@ApiOperationSupport(order = 2)
	@Operation(summary = "删除历史搜索", description = "删除历史搜索")
	@Parameters({
	   @Parameter(name = "id",description = "订单id", required = false),
	})
	@DeleteMapping("/delete")
	public R deleteSearch(@RequestParam(value = "id", required = false) Long id) {
		Long uid = SecurityUtils.getUser().getId();
		userHistorySearchService.remove(
					Wrappers.lambdaQuery(UserHistorySearch.class)
							.eq(UserHistorySearch::getUid, uid)
							.eq(ObjectUtil.isNotNull(id), UserHistorySearch::getId, id)
				);
        return R.ok();
	}

	@Inner(false)
	@ApiOperationSupport(order = 3)
	@Operation(summary = "热搜", description = "热搜")
	@GetMapping("/popular")
	public R<List<HotSearch>> getPopulorSerach() {
//		return R.ok(userHistorySearchService.getPopularSearch());
		List<HotSearch> list = hotSearchService.list(
				Wrappers.lambdaQuery(HotSearch.class)
				.eq(HotSearch::getIsShow, BizCst.CommonBool.yes)
				.eq(HotSearch::getShopId, 0)
				.orderByAsc(HotSearch::getSort)
		);

        return R.ok(list);
	}

}
